package part1.task2.sorts;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadMergeSort extends Thread {
    private volatile int arr[];
    private AtomicInteger rank;
    private int maxRank;
    public ThreadMergeSort(int[] a,int maxRank) {
        setDaemon(true);
        rank =new AtomicInteger(1);
        this.arr = a;
        this.maxRank=maxRank;
    }
    private ThreadMergeSort(int[] a,AtomicInteger rank,int maxRank) {
        setDaemon(true);
        this.rank=rank;
        this.arr = a;
        this.maxRank=maxRank;
    }

    @Override
    public void run() {
        arr=sort(arr);
    }

    private int[] sort(int a[]){
        if (a.length<2)
            return a;
        if (rank.get()==maxRank){
            Arrays.sort(a);
            return a;
        }else {
            MergeSort.Pair pair = MergeSort.split(a);

            rank.incrementAndGet();
            ThreadMergeSort t =new ThreadMergeSort(pair.b,rank,maxRank);
            t.start();
            a=sort(pair.a);

            try {
                t.join();
                a=MergeSort.merge(t.getResult(),a);
                return a;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }


    public int[] getResult(){
        return arr;
    }
}
